﻿using MediatR;
using SmartProduction.Domain;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.BomCommand;

namespace SmartProduction.Read.API.Application.CommandHandlers.BomCommandHandler
{
    /// <summary>
    /// 处理显示BOM命令
    /// </summary>
    public class BomQueryCommandHandler : IRequestHandler<BomQueryCommand, APIResult<APIPaing<Bom>>>
    {
        /// <summary>
        /// Bom仓储
        /// </summary>
        private readonly IBaseRepository<Bom> bomRepository;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="bomRepository">Bom仓储</param>
        public BomQueryCommandHandler(IBaseRepository<Bom> bomRepository)
        {
            this.bomRepository = bomRepository;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">重置</param>
        /// <returns>返回集合</returns>
        public async Task<APIResult<APIPaing<Bom>>> Handle(BomQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaing<Bom>> result=new APIResult<APIPaing<Bom>>();
            var entity= bomRepository.GetAll().Result;
            if (!string.IsNullOrEmpty(request.BomNode))
            {
                entity=entity.Where(x=>x.BomNode==request.BomNode);
            }
            if (!string.IsNullOrEmpty(request.FinishedName))
            {
                entity = entity.Where(x => x.FinishedName.Contains( request.FinishedName));
            }
            APIPaing<Bom> paing = new APIPaing<Bom>();
            result.Code = APIEnums.查询成功;
            result.Msg= APIEnums.查询成功.ToString();
            paing.TotalCount= entity.Count();
            paing.PageCount = (int)Math.Ceiling(paing.TotalCount * 1.0/ request.PageSize );
            paing.Items=entity.OrderByDescending(x=>x.BomId).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
            result.data=paing;
            return await Task.FromResult(result);
        }
    }
}
